package webserver

import (
	"fmt"
	"gitee.com/ichub/webcli/common/base/baseconfig"
	"gitee.com/ichub/webcli/common/base/basedto"
	"gitee.com/ichub/webcli/common/ichubconfig"
	"gitee.com/ichub/webcli/common/ichublog"
	"github.com/gin-gonic/gin"
	"github.com/micro/go-micro/v2/logger"
	"github.com/micro/go-micro/v2/registry"
	"github.com/micro/go-micro/v2/registry/etcd"
	"github.com/micro/go-micro/v2/web"
	"net/http"
	"path"
	"runtime"
	"time"
)

/*
@Title    文件名称: ichub_webserver.go
@Description  描述: WEB服务端通用启动与注册

@Author  作者: leijianming@163.com  时间(2024-02-18 22:38:21)
@Update  作者: leijianming@163.com  时间(2024-02-18 22:38:21)
*/
type IchubWebServer struct {
	//服务名称
	ServerName string
	Port       int
	// etcd注册服务器地址  xxx.xxx.xxx.xxx:xx
	Etcdhost string
	Registry registry.Registry

	MetaData *map[string]string
}

func New(serverDto *baseconfig.WebServerDto) *IchubWebServer {
	fmt.Println("New serverName = ", serverDto)

	web := &IchubWebServer{
		ServerName: serverDto.ServerName,
		Port:       serverDto.ServerPort,
		Etcdhost:   serverDto.EtcdHost,

		MetaData: &map[string]string{
			"version": "2024",
			"domain":  "ichub WEBSERVER",
		},
	}

	return web
}
func (webserver *IchubWebServer) getPath() string {
	_, filename, _, _ := runtime.Caller(0)
	var configBaseDir = path.Dir(filename)
	return configBaseDir
}
func (webserver *IchubWebServer) ini() {
	//新建一个consul注册的地址，也就是我们consul服务启动的机器ip+端口
	webserver.Registry = etcd.NewRegistry(
		registry.Addrs(webserver.Etcdhost),
	)

}
func (webserver *IchubWebServer) StartWeb(handler func() *[]WebHandler) web.Service {
	webserver.ini()

	var webrouters = WebRouters{FuncRegister: handler}

	microService := web.NewService(
		web.Metadata(*webserver.MetaData),
		web.Name(webserver.ServerName),       //"web.ichubengine.ichub.com"),
		web.RegisterTTL(time.Second*30),      //设置注册服务的过期时间
		web.RegisterInterval(time.Second*20), //设置间隔多久再次注册服务
		web.Address(fmt.Sprintf(":%d", webserver.Port)),
		web.Handler(webrouters.BuildRouter()),
		web.Registry(webserver.Registry),
	)

	fmt.Println("领域驱动设计，测试驱动开发！")
	fmt.Printf("第三代规则引擎启动IchubEngine server will starting(listening port=%d)...\n", webserver.Port)

	// Run service
	if err := microService.Run(); err != nil {
		logger.Fatal(err)
	}

	return microService
}
func RegisterRouter() *[]WebHandler {

	return &[]WebHandler{
		{
			http.MethodGet,
			"/",
			func(c *gin.Context) {
				c.IndentedJSON(http.StatusOK, (&basedto.IchubResult{}).SuccessData("Hello World"))
			},
		},
	}
}

func DemoWebServer() {

	var config = ichubconfig.New(ichubconfig.ConfigfileIchubengine)
	serverDto := config.ReadIchubWebServer()

	ichublog.IchubLog.Println("serverDto=", serverDto)
	var server = New(serverDto)

	//注册服务
	server.StartWeb(RegisterRouter)

}
